package com.chinawayltd.ews.sample.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chinawayltd.ews.sample.config.InterfaceConfig;
import com.chinawayltd.ews.sample.manager.openApi.OpenApiManager;
import com.chinawayltd.ews.sample.mapper.TOrgMapper;
import com.chinawayltd.ews.sample.model.OrgTreeNode;
import com.chinawayltd.ews.sample.model.TOrg;
import com.chinawayltd.ews.sample.model.TOrgExample;
import com.chinawayltd.ews.sample.model.openApi.OrgDTO;
import com.chinawayltd.ews.sample.service.SynchroOrgService;
import com.chinawayltd.ews.sample.util.map.MapUtils;

/**
 * @program: greeProject.timingTaskCenter
 * @description:
 * @author: xiazj
 * @create: 2018-05-25 13:22
 **/
@Service
public class SynchroOrgServiceImpl implements SynchroOrgService {

    @Autowired
    private OpenApiManager openApiManager;
    @Autowired
    private TOrgMapper tOrgMapper;

    private final SimpleDateFormat SDF_DATE_TIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional
    public void synchroOrgData() throws Exception {
        List<OrgDTO> dataList = openApiManager.getOrgList(InterfaceConfig.ORG_CODE);
        if(dataList != null && !dataList.isEmpty()) {
            List<OrgTreeNode> orgTreeNodes = this.listToTree(dataList);
            List<TOrg> existOrgList = tOrgMapper.selectByExample(new TOrgExample());
            Map<String, TOrg> existOrgMap = MapUtils.listToMap(existOrgList, "g7sid");
            this.storingData(orgTreeNodes, null, existOrgMap);
        }
    }

    /**
     * 把数据递归保存到数据库中
     * @param orgTreeNodes
     */
    private void storingData(List<OrgTreeNode> orgTreeNodes, Long parentId, Map<String, TOrg> existOrgMap) throws ParseException {
        final Date now = new Date();
        for (OrgTreeNode treeNode : orgTreeNodes) {
            TOrg temp = new TOrg();
            temp.setParentId(parentId);
            temp.setG7sid(treeNode.getId());
            temp.setRoot(treeNode.getOrgroot());
            temp.setParentCode(treeNode.getCreateorgcode());
            temp.setCode(treeNode.getOrgcode());
            temp.setName(treeNode.getName());
            if(StringUtils.isNotBlank(treeNode.getCreatetime()))
                temp.setCreateTime(SDF_DATE_TIME.parse(treeNode.getCreatetime()));
            temp.setUpdateTime(now);

            TOrg oldOrg = existOrgMap.get(treeNode.getId());
            //修改
            if(oldOrg != null){
                temp.setId(oldOrg.getId());
                tOrgMapper.updateByPrimaryKey(temp);
            }else{//新增
                tOrgMapper.insert(temp);
            }
            List<OrgTreeNode> children = treeNode.getChildren();
            if(!children.isEmpty())storingData(children, temp.getId(), existOrgMap);
        }
    }

    /**
     * 把机构列表整理成树的形态返回
     * @param dataList
     * @return
     */
    private List<OrgTreeNode> listToTree(List<OrgDTO> dataList) {
        List<OrgTreeNode> result = new ArrayList<>();
        Map<String, OrgTreeNode> treeNodeMap = new HashMap<>();

        //第一，先把所有节点转成一个map
        for (OrgDTO orgDTO : dataList) {
            OrgTreeNode node = new OrgTreeNode();
            BeanUtils.copyProperties(orgDTO, node);
            treeNodeMap.put(orgDTO.getId(), node);
        }

        //第二，循环把所有树的子节点都挂载到对应的父节点上
        for (String key : treeNodeMap.keySet()) {
            OrgTreeNode node = treeNodeMap.get(key);
            String parentId = node.getParentid();
            OrgTreeNode parentNode = treeNodeMap.get(parentId);
            //把当前子节点添加到父节点的树枝上
            if(parentNode != null){
                parentNode.getChildren().add(node);
            }else if(InterfaceConfig.ORG_CODE.equals(node.getOrgcode())){//把整棵树的父节点找到
                result.add(node);
            }
        }

        return result;
    }

}
